import { handleLogin, userProfile, userDetails } from '@/api/user'
import { setToken, getToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'

const state = {
  token: getToken('hrToken') || '', // token
  userInfo: {} // 用户资料
}

const mutations = {
  // 给token赋值
  setToken(state, data) {
    setToken('hrToken', data)
    state.token = data
  },
  // 资料赋值
  setInfo(state, data) {
    state.userInfo = data
  },
  // 删除token
  removeTK(state) {
    state.token = ''
    removeToken('hrToken')
  },
  // 删除资料
  removeuserInfo(state) {
    state.userInfo = ''
  }
}

const actions = {
  // 登录请求
  async Login(store, data) {
    const res = await handleLogin(data)
    store.commit('setToken', res)
  },
  // 获取用户资料请求
  async userMaterial(store) {
    const res = await userProfile()
    const data = await userDetails(res.userId)
    store.commit('setInfo', { ...res, ...data })
    // 获取id请求头像名字数据
  },
  // 退出时删除数据
  removeUserList(store) {
    store.commit('removeTK')
    store.commit('removeuserInfo')
    resetRouter()
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

